﻿using LuckyShell.ShellOrders;
using LuckyShell.ShellValues;

namespace LuckyShell.Commands;

public class WebGetCommand(List<ShellValue> values) : Command(values)
{
    public override object Run(ref VariateManager manager)
    {
        switch (Values.Count)
        {
            case 1:
                var address = Values[0].GetValue(ref manager);
                if (address is string s)
                    Task.Run(() => DownloadFile(s));
                break;
            case 2:
                var address_2 = Values[0].GetValue(ref manager);
                var path = Values[1].GetValue(ref manager);
                if (address_2 is string address2 && path is string pathString)
                    Task.Run(() => DownloadFile(address2, pathString));
                break;
        }

        return new VoidValue();
    }

    //https://download.visualstudio.microsoft.com/download/pr/93961dfb-d1e0-49c8-9230-abcba1ebab5a/811ed1eb63d7652325727720edda26a8/dotnet-sdk-8.0.100-win-x64.exe
    private async Task DownloadFile(string address)
    {
        var downloadPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
        await DownloadFile(address, downloadPath);
    }

    private async Task DownloadFile(string address, string path)
    {
        using var client = new HttpClient();
        using var response = await client.GetAsync(address, HttpCompletionOption.ResponseHeadersRead);
        response.EnsureSuccessStatusCode(); // 检查响应成功，否则抛出异常
        var savePath = "";
        if (Directory.Exists(path))
        {
            var contentDisposition = response.Content.Headers.ContentDisposition?.ToString();
            if (string.IsNullOrEmpty(contentDisposition))
            {
                savePath = address.Split("/")[^1];
            }
            else
            {
                var fileName = new System.Net.Mime.ContentDisposition(contentDisposition).FileName;
                savePath = Path.Combine(path, fileName!);
            }
        }
        else if (File.Exists(path))
        {
            savePath = path;
        }

        if (string.IsNullOrEmpty(savePath)) throw new Exception("SavePath is Null or Empty");
        await using var fileStream = new FileStream(savePath, FileMode.Create, FileAccess.Write, FileShare.None);
        Console.WriteLine("Downloading...(It has been placed in another process for processing.)");
        await Task.Run(() => response.Content.CopyToAsync(fileStream));
        Console.WriteLine($"Done! it's in {savePath}");
        Console.WriteLine();
    }
}